<template>
  <div class="app-container checked">
    <div class="filter-container">
      <el-input v-show="activeName === 'first'" v-model.trim="query.query.purchaseOrderNo" clearable
        placeholder="请输入订单编号" @keyup.enter.native="search" />
      <el-input v-show="activeName === 'first'" v-model.trim="query.query.customerName" clearable placeholder="请输入供应商名称"
        @keyup.enter.native="search" />
      <el-input v-show="activeName === 'first'" v-model.trim="query.query.material" clearable placeholder="请输入物料编号"
        @keyup.enter.native="search" />
      <el-select v-show="activeName === 'second'" v-model="query.query.customerName" placeholder="请选择客户名称" clearable>
        <el-option v-for="item in partnersListData" :key="item.partnerCode" :label="item.partnerName"
          :value="item.partnerName">
        </el-option>
      </el-select>
      <el-select v-show="activeName === 'second'" v-model="query.query.materialName" placeholder="请输入对应我方物料名称"
        clearable>
        <el-option v-for="item in materialPageListData" :key="item.materialNo" :label="item.materialName"
          :value="item.materialName">
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="search">{{ $t('table.search') }}</el-button>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClickTab">
      <el-tab-pane label="采购订单" name="first">
        <el-table :data="tableData" highlight-current-row border
          :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
          <el-table-column prop="purchaseOrderNo" label="订单编号" fixed="left" />
          <el-table-column prop="enduserName" label="供应商名称" />
          <el-table-column prop="materialName" label="物料名称" />
          <el-table-column prop="orderedQty" label="订购数量" />
          <!-- <el-table-column prop="sellingPrice" label="销售价格" /> -->
          <!-- <el-table-column prop="shipToName" label="收货地" />
      <el-table-column prop="arriveDate" label="原到达日期">
        <template slot-scope="{row}">
          <span>{{ row.arriveDate | parseTime('{y}-{m}-{d}') }}</span>
        </template>
</el-table-column>
<el-table-column prop="productDate" label="原生产日期">
  <template slot-scope="{row}">
          <span>{{ row.productDate | parseTime('{y}-{m}-{d}') }}</span>
        </template>
</el-table-column>
<el-table-column prop="latestArriveDate" label="最新到达日期">
  <template slot-scope="{row}">
          <span>{{ row.latestArriveDate | parseTime('{y}-{m}-{d}') }}</span>
        </template>
</el-table-column>
<el-table-column prop="latestProductDate" label="最新生产日期">
  <template slot-scope="{row}">
          <span>{{ row.latestProductDate | parseTime('{y}-{m}-{d}') }}</span>
        </template>
</el-table-column>
<el-table-column prop="rddItem" label="预计交货日期">
  <template slot-scope="{row}">
          <span>{{ row.rddItem | parseTime('{y}-{m}-{d}') }}</span>
        </template>
</el-table-column>
<el-table-column prop="materialAvailDate" label="确认交货日期">
  <template slot-scope="{row}">
          <span>{{ row.materialAvailDate | parseTime('{y}-{m}-{d}') }}</span>
        </template>
</el-table-column>
<el-table-column prop="deliveryNo" label="交货单号" /> -->
          <el-table-column prop="createdOn" label="创建日期">
            <template slot-scope="{row}">
              <span>{{ row.createdOn | parseTime('{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="amortizationPrice" label="摊销金额" />
          <el-table-column width="80px" :label="$t('table.actions')" fixed="right">
            <template slot-scope="{ row, $index }">
              <div>
                <el-button size="mini" type="primary" @click="handleDetail(row)">明细</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="销售订单" name="second">
        <el-table :data="tableData" style="width: 100%;margin-bottom: 20px;"
          row-key="id" highlight-current-row border :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }" @cell-click="cellClick">
          <el-table-column prop="customerOrderNo" label="客户订单号" />
          <el-table-column prop="salesOrderNumber" label="销售订单号" />
          <el-table-column prop="customerName" label="客户名称" />
          <el-table-column prop="customerMaterial" label="购买商品名称" />
          <el-table-column prop="materialName" label="对应我方物料名称" />
          <el-table-column prop="materialNo" label="对应我方物料代码" />
          <el-table-column prop="sendGoodsDate" label="需求日期">
            <template slot-scope="{ row: { sendGoodsDate } }">
              {{ getMoment(sendGoodsDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="orderGoodsNum" label="订单数量" />
          <el-table-column prop="amortizationPrice" label="摊销金额" />
          <!-- <el-table-column prop="unitTaxedPrice" label="单价（含税）" width="130" />
          <el-table-column prop="receivableAmount" label="应收金额（含税）" width="140" />
          <el-table-column prop="frequency" label="需求状态" width="100">
            <template slot-scope="{ row: { demandState } }">
              <el-tag :type="demandState == 0 ? 'danger' : 'success'">{{ demandState == 0 ? "未" : "已" }}转需求</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="outStoreGoodsNum" label="已发货数量" width="100" />
          <el-table-column prop="sendGoodsState" label="发货状态" width="100">
            <template slot-scope="{ row: { sendGoodsState } }">
              {{ getSendGoodsState(sendGoodsState) }}
            </template>
          </el-table-column> -->
          <el-table-column width="80px" :label="$t('table.actions')" align="center" fixed="right">
            <template slot-scope="{ row, $index }">
              <el-button size="mini" type="primary" @click="handleDetail(row)">摊销</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <pagination v-show="total > 0" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
      @pagination="getInfo" />
    <el-dialog :close-on-click-modal="false" :visible.sync="fundDialogVisible" title="明细">
      <el-button style="margin-bottom:10px" type="primary" icon="el-icon-plus" @click="handleClick">
        新增
      </el-button>
      <el-table :data="fundTableData" highlight-current-row border :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }">
        <el-table-column prop="price" label="摊销金额" />
        <el-table-column prop="reason" label="摊销原因" />
        <el-table-column width="80px" :label="$t('table.actions')" fixed="right">
          <template slot-scope="{ row, $index }">
            <div>
              <el-button size="mini" type="danger" @click="handleDel(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog @closed="txHandleClose" :close-on-click-modal="false" :visible.sync="txDialogVisible" title="新增">
      <el-form ref="fundRuleForm" :model="fund" label-width="100px" :rules="fundRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="摊销金额" prop="price">
              <el-input v-model.trim="fund.price" @input="fund.price = fund.price.replace(/[^\d|\.]/g, '')"
                placeholder="请输入摊销金额" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="摊销原因" prop="reason">
              <el-input v-model.trim="fund.reason" placeholder="请输入摊销原因" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="txDialogVisible = false">{{ $t('permission.cancel') }}</el-button>
        <el-button type="primary" @click="fundConfirm">{{ $t('permission.save') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { orderPageList, ordersOtcGetAmortizationList, smSellOrderGetAmortizationList, ordersOtcGetdelAmortization, ordersOtcSaveAmortizationList, smSellOrderSaveAmortizationList } from '@/api/productionPlan'
import {
  orderPageList as orderPageListSale,
  accGetYsYfValue
} from "@/api/andonProblemLevel";
import { partnersList } from "@/api/andonProblemManager";
import { materialPageList } from "@/api/departentment";
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { deepClone } from '@/utils'
import moment from "moment";
export default {
  name: 'Productionplan',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      activeName: 'first',
      selectedList: [],
      tableData: [],
      fundDialogVisible: false,
      fundRules: {
        price: [
          { required: true, message: '请选择摊销金额', trigger: 'change' }
        ],
        reason: [
          { required: true, message: '请输入摊销原因', trigger: 'blur' }
        ]
      },
      fund: {},
      query: {
        pageSize: 10,
        pageIndex: 1,
        query: {}
      },
      fundTableData: [],
      txDialogVisible: false,
      materialPageListData: [],
      partnersListData: []
    }
  },
  mounted() {
    this.getInfo()
    this.getPartnersList();
    this.getMaterialPageList();
  },
  methods: {
    getPartnersList() {
      partnersList({
        pageIndex: 1,
        pageSize: 10000,
        query: {
          partnerType: 1
        }
      }).then(res => {
        const { records } = res;
        this.partnersListData = records;
      });
    },
    getMaterialPageList() {
      materialPageList({
        pageIndex: 1,
        pageSize: 1000
      }).then(res => {
        const { records } = res;
        this.materialPageListData = records;
      });
    },
    getSendGoodsState(val) {
      if (val == '0') {
        return "未发货";
      } else if (val == '1') {
        return "部分发货";
      } else if (val == '2') {
        return "关闭";
      }
    },
    async getInfoSale() {
      const { records, total } = await orderPageListSale(this.query);
      // if (records.length) {
      //   const sellOrderIds = records.map(item => item.idStr).join(",");
      //   const formData = new FormData();
      //   formData.append("sellOrderIds", sellOrderIds);
      //   const params = new URLSearchParams(formData);
      //   const data = await accGetYsYfValue(params);
      //   data.forEach(item => {
      //     try {
      //       records.forEach(i => {
      //         if (item.sellOrderId === i.idStr) {
      //           this.$set(i, "inAdvanceAmountCopy", item.price);
      //           throw new Error();
      //         }
      //       });
      //     } catch (err) { }
      //   });
      // }
      this.tableData = records;
      this.total = total;
    },
    getMoment(day) {
      return moment(day).format("YYYY-MM-DD");
    },
    handleClickTab(e) {
      this.query.pageIndex = 1
      this.query.query = {}
      this.tableData = []
      if (this.activeName === 'second') {
        this.query.query.state = 2
      }
      this.getInfo()
    },
    txHandleClose() {
      // this.fund = {}
      this.$refs['fundRuleForm'].resetFields()
    },
    async handleDetail(item) {
      this.fund = deepClone(item)
      await this.getOrdersOtcGetAmortizationList()
      this.fundDialogVisible = true
    },
    async getOrdersOtcGetAmortizationList() {
      if (this.activeName === 'first') {
        this.fundTableData = await ordersOtcGetAmortizationList({ purchaseOrderNo: this.fund.purchaseOrderNo })
      } else {
        this.fundTableData = await smSellOrderGetAmortizationList({ sellOrderNo: this.fund.salesOrderNumber })
      }
    },
    async fundConfirm() {
      this.$refs['fundRuleForm'].validate(async (valid) => {
        if (valid) {
          const {purchaseOrderNo,internalOrderNumber,salesOrderNumber,price,reason} = this.fund
          let params = {
            price,
            reason
          }
          if (this.activeName === 'first') {
            params.purchaseOrderNo = purchaseOrderNo
            params.internalOrderNumber = internalOrderNumber
            await ordersOtcSaveAmortizationList(params)
          } else {
            params.salesOrderNo = salesOrderNumber
            await smSellOrderSaveAmortizationList(params)
          }
          this.getOrdersOtcGetAmortizationList()
          this.$message.success('操作成功！')
          this.txDialogVisible = false
        }
      })
    },
    handleClick() {
      this.txDialogVisible = true
    },
    handleDel(row) {
      this.$confirm('此操作将永久删除该摊销明细, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await ordersOtcGetdelAmortization(row.id)
        this.$message.success('删除成功！')
        this.getOrdersOtcGetAmortizationList()
      })
    },
    async getInfo() {
      if (this.activeName === 'first') {
        const { records, total } = await orderPageList(this.query)
        this.tableData = records
        this.total = total
      } else {
        this.getInfoSale()
      }
    },
    search() {
      this.query.pageIndex = 1
      this.getInfo()
    }
  }
}
</script>
